package top.meeting.room.common.base;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.kit.HttpKit;
import com.jfinal.kit.StrKit;
import top.meeting.room.common.kit.BeanKit;

/**
 * 我有故事，你有酒么？
 * JKhaled created by yunqisong@foxmail.com 2017/7/22
 * FOR : 基本Controller
 */
public abstract class BaseController extends BaseRender {

    protected String jsonString = null;

    /**
     * RequsetBody 的数据转化出来
     *
     * @return
     */
    public String getPara() {
        if (getRequest() != null && StrKit.notBlank(getRequest().getContentType())) {
            if (getRequest().getContentType().contains("json") || getRequest().getContentType().contains("application/x-www-form-urlencoded")) {
                if (jsonString == null) jsonString = HttpKit.readData(getRequest());
                if (StrKit.notBlank(jsonString)) return jsonString;//数据直接从request中读取出来
            }
        }
        return super.getPara();
    }

    /**
     * RequestBody 中的JSON数据直接读成bean
     *
     * @param clazz
     * @param <T>
     * @return
     */
    public <T> T getJsonParaToObj(Class<T> clazz) {
        return JSON.parseObject(getPara(), clazz);
    }


    /**
     * UrlPara 中的JSON数据直接读成bean
     *
     * @param clazz
     * @param <T>
     * @return
     */
    public <T> T getUrlParaToObj(Class<T> clazz) {
        return BeanKit.map2Bean(getParaMap(), clazz);
    }

    /**
     * RequsetBody 的数据转化出来
     *
     * @return
     */
    public String getPara(String name) {
        if (getRequest() != null && StrKit.notBlank(getRequest().getContentType())) {
            if (getRequest().getContentType().contains("json") || getRequest().getContentType().contains("application/x-www-form-urlencoded")) {
                if (jsonString == null) jsonString = getPara();
                if (StrKit.notBlank(jsonString)) return JSONObject.parseObject(jsonString).getString(name);
            }
        }
        return super.getPara(name);
    }

    /**
     * RequsetBody 的用JSONObject数据转化出来
     *
     * @return
     */
    public JSONObject getParaToJson() {
        return JSONObject.parseObject(getPara());
    }

    /**
     * RequsetBody 的用JSONObject数据转化出来
     *
     * @return
     */
    public JSONObject getParaToJson(String name) {
        return JSONObject.parseObject(getPara(name));
    }


}
